const labelService = require('../service/label.service')

const verifyLabelExists = async (ctx, next) => {
  //1 获取所有传递过来的labels
  const { labels } = ctx.request.body
  //2 判断所有的labels是否存在在label表中
  const newLabels = []
  for (const name of labels) {
    // console.log(name)
    const result = await labelService.queryLabelByName(name)
    // 如果存在获取对应的labelid
    const labelObj = { name }
    if (result) {
      labelObj.id = result.id
    } else {
      // 如果不存在，插入到label表中
      const insertResult = await labelService.create(name)
      labelObj.id = insertResult.insertId
    }
    newLabels.push(labelObj)
  }
  //   3 所有的label都变成
  //   console.log(newLabels)
  //   [ { name: '西游记', id: 8 }, { name: '三国演义', id: 9 } ]
  //   return newLabels
  ctx.labels = newLabels
  await next()
}

module.exports = { verifyLabelExists }
